package com.demo;

//import lombok.extern.slf4j.Slf4j;
import com.sun.deploy.util.StringUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

//@Slf4j
public class Main {

    private static String tomcatBasePath = "C:\\ProgramFiles\\tomcat\\";
    //Nginx根目录，运行目录
//    private static String nginxBasePath = "C:\\ProgramFiles\\nginx-web-9999\\";
    private static String nginxBasePath = "C:\\ProgramFiles\\nginx-tomcat-8888\\";
    //监听命令目录
    private static String cmdBasePath = "C:\\share\\cmd\\";

    public static void main(String[] args) throws InterruptedException {
        //循环监听磁盘变化
        Process process ;
        BufferedReader br;
        String line = null;
        int exitValue;
        while(true){
            System.out.print('.');
            //检查是否要重启Nginx
            File fileNginxRestart = new File(cmdBasePath+"nginx.restart");
            if(fileNginxRestart.exists()){
                try {
                    System.out.println();
                    System.out.println("重启Nginx");
                    //执行命令
                    process = Runtime.getRuntime().exec("taskkill /im nginx.exe /f");
                    //获取输出
                     br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    //输出
                    while((line = br.readLine()) != null) {
                        System.out.println(line);
                    }
                    //返回
                     exitValue = process.waitFor();
                    System.out.println("关闭Nginx进程返回值：" + exitValue);
                    //启动
                    process = Runtime.getRuntime().exec("nginx.exe",null,new File(nginxBasePath));
                    //获取输出，Nginx执行运行后没有返回值
//                     br = new BufferedReader(new InputStreamReader(process.getInputStream()));
//                    //输出
//                    while((line = br.readLine()) != null) {
//                        System.out.println(line);
//                    }
                    //返回
//                     exitValue = process.waitFor();
//                    System.out.println("启动Nginx进程返回值：" + exitValue);
                    //删除命令文件
                    fileNginxRestart.delete();
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //检查是否要重启Tomcat
            File fileTomcatRestart = new File(cmdBasePath+"tomcat.restart");
            if(fileTomcatRestart.exists()){
                System.out.println();
                System.out.println("重启tomcat");
                //最大部署9台
                for(int i=8081;i<=8089;i++){
//                    C:\ProgramFiles\tomcat\apache-tomcat-8081\bin
                    String tomcatPath = tomcatBasePath + "apache-tomcat-"+i+"\\bin\\";
                    File fileTomcatPath = new File(tomcatPath);
                    //如果仅启用5台，则后续跳过
                    if(!fileTomcatPath.exists()){
                        System.out.println("未部署跳过"+tomcatPath);
                        continue;
                    }
                    //
//                    String tomcatShutdown = tomcatPath+"\\shutdown.bat";
//                    String tomcatStartup = tomcatPath+"\\startup.bat";
                    //执行命令
                    try {
                        //执行shutdown后，因为Tomcat是单独进程在跑，服务关闭后，进程会再次重启服务
//                        process = Runtime.getRuntime().exec("shutdown.bat",null,fileTomcatPath );
//                        //获取输出
//                        br = new BufferedReader(new InputStreamReader(process.getInputStream()));
//                        //输出
//                        while((line = br.readLine()) != null) {
//                            System.out.println(line);
//                        }
//                        //返回
//                        exitValue = process.waitFor();
//                        System.out.println("关闭Tomcat"+i+"进程返回值：" + exitValue);
                        //查询该端口的进程ID，然后使用进程ID关闭进程
//                        "netstat -ano|findstr "+i
                        process = Runtime.getRuntime().exec("netstat -ano",null,new File("C:\\Windows\\System32\\"));
                        br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                        while((line = br.readLine()) != null) {
//                            C:\Users\Administrator>netstat -ano|findstr 8082
//                            TCP    0.0.0.0:8082           0.0.0.0:0              LISTENING       5460
//                            TCP    [::]:8082              [::]:0                 LISTENING       5460
                            System.out.println(line);
                            if(line.trim()=="") break;
                            //
                            int x = line.lastIndexOf(' ');
                            if(x==-1)continue;
                            String pid = line.substring(x).trim();
//                            try {
//                                process = Runtime.getRuntime().exec("taskkill /pid "+pid+" /f");
//                                //获取输出
//                                SequenceInputStream out = new SequenceInputStream(process.getInputStream(),process.getErrorStream());
//                                br = new BufferedReader(new InputStreamReader(out));
//                                //输出
//                                while((line = br.readLine()) != null) {
//                                    System.out.println(line);
//                                }
//                                //返回
//                                exitValue = process.waitFor();
//                                System.out.println("关闭Tomcat"+i+"进程"+pid+"返回值：" + exitValue);
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }
                            break;
                        }
                        //
//                        process = Runtime.getRuntime().exec("startup.bat",null, fileTomcatPath);
//                        //获取输出
//                        br = new BufferedReader(new InputStreamReader(process.getInputStream()));
//                        //输出
//                        while((line = br.readLine()) != null) {
//                            System.out.println(line);
//                        }
//                        //返回
//                        exitValue = process.waitFor();
//                        System.out.println("重启Tomcat进程"+i+"返回值：" + exitValue);

                    } catch (IOException e) {
                        System.out.println("error");
                        e.printStackTrace();
                    }
                }
                //删除命令文件
                fileTomcatRestart.delete();
            }
            //检查是否有要更新的Tomcat包

            //等待
            Thread.currentThread().sleep(1*1000);
        }



//        args = new String[]{"8088"};
//        Main manager = new Main();
//        if(args.length!=1){
//            System.out.println("需要输入端口号");
//        }
//        String portP = args[0];
//        Main.port = Integer.parseInt(portP);
//        System.out.println("监听端口号："+port);
//        manager.doListen();
    }

//    public void doListen() {
//        ServerSocket server;
//        try {
//            server = new ServerSocket(Main.port );
//            while (true) {
//                Socket client = server.accept();
//                new Thread(new SSocket(client)).start();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

//    class SSocket implements Runnable {
//        Socket client;
//
//        public SSocket(Socket client) {
//            this.client = client;
//        }
//
//        public void run() {
//            DataInputStream input;
//            DataOutputStream output;
//            try {
//                input = new DataInputStream(client.getInputStream());
//                output = new DataOutputStream(client.getOutputStream());
//                Thread.sleep(5000L);
//                String data = input.readUTF();
//                output.writeUTF("Recive1:  " + data);
////                log.info("接口名称 access {}", data);
//                System.out.println("接口名称 access {}"+ data);
//                data = input.readUTF();
//                output.writeUTF("Recive2:  " + data);
////                log.info("接收的数据 {}", data);
//                System.out.println("接收的数据 {}"+ data);
//            } catch (IOException e) {
//                e.printStackTrace();
//            } catch (Exception e) {}
//        }
//    }
}
